﻿using System;
using System.IO;
using DllShepherd.Core.Esri;
using DllShepherd.Core.Esri.Server;

namespace DllShepherd.ArcGisServerTools
{
    class Program
    {
        static void Main(string[] args)
        {
            if (args.Length < 3)
            {
                Console.WriteLine("Wrong usage:");
                Console.WriteLine("-[c/p/r/g] MSD_file_path [connection string] [new file name] [Server name]");
                Console.WriteLine("-c :Change connection to DB in MSD file");
                Console.WriteLine("  -c MSD_file_path [connection string] [new file name]");
                Console.WriteLine("-p :Publish MSD file to Server from server (msd file can be in relative path)");
                Console.WriteLine("  -p MSD_file_path [Server name] [optional: Service Name]");
                Console.WriteLine("-pr :Publish MSD file to Server from remote location (msd file must be in absolute path)");
                Console.WriteLine("  -pr MSD_file_path [Server name] [optional: Service Name]");
                Console.WriteLine("-r :Clear Rest API Cache");
                Console.WriteLine("  -r [Server name] [admin user name] [admin password]");
                Console.WriteLine("-g :Get service configuration");
                Console.WriteLine("  -g [Server name] [Service name]");
                return;
            }

            var option = args[0].ToLower();
            var msdFilePath = args[1];
            EsriInitilization.Start();

            switch (option)
            {
                case "-c":
                    ChangeConnection(msdFilePath, args[2], args[3]);
                    break;
                case "-p":
                    PublishToServer(msdFilePath, args[2], args.Length >= 4 ? args[3] : "MapDbService");
                    break;
                case "-pr":
                    ArcGisServerUtils.PublishToServer(msdFilePath, args[2], args.Length >= 4 ? args[3] : "MapDbService");
                    break;
                case "-r":
                    var response = ArcGisServerUtils.ClearCache(args[1], args[2], args[3]);
                    Console.WriteLine("Cleared cache, server response: " + response);
                    break;
                case "-g":
                    ArcGisServerUtils.GetServiceConfiguration(args[1], args[2]);
                    break;
            }
        }

        private static void ChangeConnection(string msdFilePath, string connectionString, string newMsdFile)
        {
            MsdUtils.ChangeConnection(msdFilePath, connectionString, newMsdFile);
        }

        private static void PublishToServer(string msdFilePath, string serverName, string serviceName)
        {
            ArcGisServerUtils.PublishToServer(Path.GetFullPath(msdFilePath), serverName, serviceName);
            Console.WriteLine("File published in Server.");
        }
    }
}
